import axios from 'axios'
import cookies from './cookies'
import format from './format'
import validation from './validation'
import api from '@/assets/api/oss'
const uploader = async (params, dir = 'MATCH/') => {
  const res = await api.getConfig({
    dir
  })
  const data = res.data.data
  const file = params.file
  const formData = new FormData()
  const suffix = file.name.slice(file.name.lastIndexOf('.') + 1)
  const filename = file.name.slice(0, file.name.lastIndexOf('.')) + '-' + new Date().getTime() + '.' + suffix
  formData.append('name', `${filename}`)
  formData.append('key', `${dir}${filename}`)
  formData.append('policy', data.policy)
  formData.append('OSSAccessKeyId', data.accessid)
  formData.append('success_action_status', 200)
  formData.append('callback', data.callback)
  formData.append('signature', data.signature)
  formData.append('file', file)
  try {
    let res = await axios.post(data.host, formData, {headers: { 'Content-Type': 'multipart/form-data' }})
    res = res.data
    return new Promise((resolve) => {
      resolve(res)
    })
  } catch (e) {
    console.log(e)
  }
}
const getPageBtns = (roles = []) => {
  const url = location.hash.replace('#', '')
  let btns = []
  roles.map(role => {
    if (role.path === url) {
      btns = role.buttons || []
    }

    role.children && role.children.map(child => {
      if (child.path === url) {
        btns = child.buttons || []
      }
    })
  })
  return btns
}
const addEvent = (obj, type, handle, flag) => {
  try { // Chrome、FireFox、Opera、Safari、IE9.0及其以上版本
    obj.addEventListener(type, handle, flag)
  } catch (e) {
    try { // IE8.0及其以下版本
      obj.attachEvent('on' + type, handle)
    } catch (e) { // 早期浏览器
      obj['on' + type] = handle
    }
  }
}
const stopEvent = (e) => {
  if (e && e.stopPropagation) {
    e.stopPropagation()
  } else if (window.event) {
    window.event.cancelBubble = true
  }
}
const removeEvent = (ele, event, fn, flag) => {
  if (ele.removeEventListener) {
    ele.removeEventListener(event, fn, flag)
  } else {
    ele.detachEvent('on' + event, fn.bind(ele))
  }
}
export default{
  ...cookies,
  ...format,
  ...validation,
  uploader,
  getPageBtns,
  addEvent,
  stopEvent,
  removeEvent
}
